package cn.auction.web;

import cn.auction.biz.AuctionBiz;
import cn.auction.biz.impl.AuctionBizImpl;
import cn.auction.entity.*;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

public class AutionController {
    AuctionBiz auctionBiz=new AuctionBizImpl();

    //查询信息
    public String showAuctionList(HttpServletRequest request, HttpServletResponse response) throws SQLException {
        try {
                int pageIndex=1;
                if(request.getParameter("pageIndex")!=null){
                        pageIndex=new Integer(request.getParameter("pageIndex"));
                }
                Auction auction=new Auction();
                if(request.getParameter("auctionDesc")!=null&&!"".equals(request.getParameter("auctionDesc"))){
                        auction.setAuctionDesc(request.getParameter("auctionDesc"));
                }
            if(request.getParameter("auctionStartTime")!=null&&!"".equals(request.getParameter("auctionStartTime"))){
                auction.setAuctionStartTime(new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("auctionStartTime")));
            }
            if(request.getParameter("auctionEndTime")!=null&&!"".equals(request.getParameter("auctionEndTime"))){
                auction.setAuctionEndTime(new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("auctionEndTime")));
            }
            if(request.getParameter("auctionName")!=null&&!"".equals(request.getParameter("auctionName"))){
                auction.setAuctionName(request.getParameter("auctionName"));
            }
            if(request.getParameter("auctionStartPrice")!=null&&!"".equals(request.getParameter("auctionStartPrice"))){
                auction.setAuctionStartPrice(Double.parseDouble(request.getParameter("auctionStartPrice")));
            }
            AuctionPage<Auction> auctionAuctionPage=auctionBiz.showAllAuction(auction,pageIndex);
            request.setAttribute("page",auctionAuctionPage);
            return "forward:/auctionList.jsp";
        }catch (Exception e){
            e.printStackTrace();
            return "/error.jsp";
        }
    }
//    public String zuShowList(HttpServletRequest request,HttpServletResponse response){
//        try {
//            int pageIndex=1;
//            if(request.getParameter("pageIndex")!=null){
//                pageIndex=new Integer(request.getParameter("pageIndex"));
//            }
//            Auction auction=new Auction();
//            if(request.getParameter("auctionDesc")!=null&&!"".equals(request.getParameter("auctionDesc"))){
//                auction.setAuctionDesc(request.getParameter("auctionDesc"));
//            }
//            if(request.getParameter("auctionStartTime")!=null&&!"".equals(request.getParameter("auctionStartTime"))){
//                auction.setAuctionStartTime(new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("auctionStartTime")));
//            }
//            if(request.getParameter("auctionEndTime")!=null&&!"".equals(request.getParameter("auctionEndTime"))){
//                auction.setAuctionEndTime(new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("auctionEndTime")));
//            }
//            if(request.getParameter("auctionName")!=null&&!"".equals(request.getParameter("auctionName"))){
//                auction.setAuctionName(request.getParameter("auctionName"));
//            }
//            if(request.getParameter("auctionStartPrice")!=null&&!"".equals(request.getParameter("auctionStartPrice"))){
//                auction.setAuctionStartPrice(Double.parseDouble(request.getParameter("auctionStartPrice")));
//            }
//            AuctionPage<Auction> auctionAuctionPage=auctionBiz.showAllAuction(auction,pageIndex);
//            request.setAttribute("page",auctionAuctionPage);
//            return "forward:/auctionList.jsp";
//        }catch (Exception e){
//            e.printStackTrace();
//            return "/error.jsp";
//        }
//        return "";
//    }
    //新增拍卖品
    public String AddAuction(HttpServletRequest request,HttpServletResponse responsed) throws SQLException, ParseException, IOException {
        PrintWriter out = responsed.getWriter();
//        System.out.println(request.getParameter("auctionName"));
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
//
          Auction auction=new Auction();
//        //endTime
//        auction.setAuctionName(request.getParameter("auctionName"));
//        auction.setAuctionStartPrice(Float.valueOf(request.getParameter("startPrice")));
//        auction.setAuctionUpset(Float.valueOf(request.getParameter("upset")));
//        auction.setAuctionStartTime(simpleDateFormat.parse(request.getParameter("startTime")));
//        auction.setAuctionEndTime(simpleDateFormat.parse(request.getParameter("endTime")));
//        auction.setAuctionPic(request.getParameter("pic"));
//        auction.setAuctionDesc(request.getParameter("desc"));
//        int result=auctionBiz.AddAuction(auction);
//        if(result>0){
//            return "redirect:/do/auction/auctionList";
//        }else{
//            return "";
//        }
        String uploadFileName = ""; //上传的文件名
        String fieldName = "";  //表单字段元素的name属性值
        //请求信息中的内容是否是multipart类型
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        //上传文件的存储路径（服务器文件系统上的绝对文件路径）
        //request.getSession().getServletContext().getRealPath("images/" );
        String uploadFilePath = request.getSession().getServletContext().getRealPath("images/" );
        System.out.println(uploadFilePath);
        //创建临时文件目录路径
        File tempPatchFile=new File("d:\\temp\\buffer");
        if(!tempPatchFile.exists())  //判断文件或目录是否存在
            tempPatchFile.mkdirs();   //创建指定的目录，包括所有必需但不存在的父目录
        if (isMultipart) {
            DiskFileItemFactory factory=new DiskFileItemFactory();
            //设置缓冲区大小4kb
            factory.setSizeThreshold(4096);
            //设置上传文件用到临时文件存放路径
            factory.setRepository(tempPatchFile);
            ServletFileUpload upload = new ServletFileUpload(factory);
            //设置单个文件的最大限制
            upload.setSizeMax(1024*3000);
            try{
                //解析form表单中所有文件
                List<FileItem> items = upload.parseRequest(request);
                Iterator<FileItem> iter = items.iterator();
                while (iter.hasNext()) {   //依次处理每个文件
                    FileItem item = (FileItem) iter.next();//普通是表单元素还是file文件域表单元素
                    if (!item.isFormField()){  //文件表单字段
                        String fileName = item.getName();
                        //通过Arrays类的asList()方法创建固定长度的集合
                        List<String> filType= Arrays.asList("gif","bmp","jpg","png");
                        String ext=fileName.substring(fileName.lastIndexOf(".")+1);//上传的文件扩展名
                        if(!filType.contains(ext))  //判断文件类型是否在允许范围内
                            out.print("上传失败，文件类型只能是gif、bmp、jpg、png");
                        else{
                            if (fileName != null && !fileName.equals("")) {
                                File fullFile = new File(item.getName());
                                File saveFile = new File(uploadFilePath, fullFile.getName());
                                item.write(saveFile);
                                uploadFileName = fullFile.getName();//上传后的文件名保留原文件名
                                //uploadFileName
                                auction.setAuctionPic(uploadFileName);
                                int indexof=uploadFileName.lastIndexOf(".");
                                auction.setAuctionPicType(uploadFileName.substring((indexof+1)));
                            }
                        }
                    }else{//普通表单元素
                        fieldName = item.getFieldName();   //表单字段的name属性值
                        if (fieldName.equals("auctionName")){
                            //输出表单字段的值
                            auction.setAuctionName(item.getString("UTF-8"));
                            //easyBuy_ProductUpdate.setName(item.getString("UTF-8"));
                        }
                        if(fieldName.equals("startPrice")){
                            auction.setAuctionStartPrice(Double.valueOf(item.getString("UTF-8")));
                            //easyBuy_ProductUpdate.setCategoryLevell(Integer.valueOf(item.getString("UTF-8")));
                        }
                        if(fieldName.equals("upset")){
                           // easyBuy_ProductUpdate.setCategoryLevel2(Integer.valueOf(item.getString("UTF-8")));
                            auction.setAuctionUpset(Double.valueOf(item.getString("UTF-8")));
                        }
                        if(fieldName.equals("startTime")){
                           // easyBuy_ProductUpdate.setCategoryLevel3(Integer.valueOf(item.getString("UTF-8")));
                            auction.setAuctionStartTime(simpleDateFormat.parse(item.getString("UTF-8")));
                        }
                        if(fieldName.equals("endTime")){
                           // easyBuy_ProductUpdate.setStock(Integer.valueOf(item.getString("UTF-8")));
                            auction.setAuctionEndTime(simpleDateFormat.parse(item.getString("UTF-8")));
                        }
                        if(fieldName.equals("desc")){
                            auction.setAuctionDesc(item.getString("UTF-8"));
                           // easyBuy_ProductUpdate.setPrice(Double.parseDouble(item.getString("UTF-8")));
                        }
                    }
                }
            }catch(FileUploadBase.SizeLimitExceededException ex){
                out.print("上传失败，文件太大，单个文件的最大限制是："+upload.getSizeMax()+"bytes!");
            }catch (Exception e) {
                e.printStackTrace();
            }

        }
        int result=auctionBiz.AddAuction(auction);
        if(result>0){
            return "redirect:/do/auction/auctionList";
        }else{
            return "redirect:/login-admin.jsp";
        }

    }
    //修改信息回显数据
    public String UpdateHuiXian(HttpServletRequest request,HttpServletResponse response) throws SQLException {
        int id=Integer.valueOf(request.getParameter("auctionUH"));
        Auction auction=auctionBiz.ShowAuctionById(id);
        request.getSession().setAttribute("auctionHui",auction);
        return "redirect:/addAuction.jsp";
    }
    //修改
    public String UpdateAuction(HttpServletRequest request,HttpServletResponse response) throws IOException, SQLException {
        PrintWriter out = response.getWriter();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        Auction auction=new Auction();
        String uploadFileName = ""; //上传的文件名
        String fieldName = "";  //表单字段元素的name属性值
        //请求信息中的内容是否是multipart类型
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        //上传文件的存储路径（服务器文件系统上的绝对文件路径）
        String uploadFilePath = request.getSession().getServletContext().getRealPath("images/" );
        //创建临时文件目录路径
        File tempPatchFile=new File("d:\\temp\\buffer");
        if(!tempPatchFile.exists())  //判断文件或目录是否存在
            tempPatchFile.mkdirs();   //创建指定的目录，包括所有必需但不存在的父目录
        if (isMultipart) {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //设置缓冲区大小4kb
            factory.setSizeThreshold(4096);
            //设置上传文件用到临时文件存放路径
            factory.setRepository(tempPatchFile);
            ServletFileUpload upload = new ServletFileUpload(factory);
            //设置单个文件的最大限制
            upload.setSizeMax(1024 * 3000);
            try {
                //解析form表单中所有文件
                List<FileItem> items = upload.parseRequest(request);
                Iterator<FileItem> iter = items.iterator();
                while (iter.hasNext()) {   //依次处理每个文件
                    FileItem item = (FileItem) iter.next();//普通是表单元素还是file文件域表单元素
                    if (!item.isFormField()) {  //文件表单字段
                        String fileName = item.getName();
                        //通过Arrays类的asList()方法创建固定长度的集合
                        List<String> filType = Arrays.asList("gif", "bmp", "jpg", "png");
                        String ext = fileName.substring(fileName.lastIndexOf(".") + 1);//上传的文件扩展名
                        if (!filType.contains(ext))  //判断文件类型是否在允许范围内
                            out.print("上传失败，文件类型只能是gif、bmp、jpg、png");
                        else {
                            if (fileName != null && !fileName.equals("")) {
                                File fullFile = new File(item.getName());
                                File saveFile = new File(uploadFilePath, fullFile.getName());
                                item.write(saveFile);
                                uploadFileName = fullFile.getName();//上传后的文件名保留原文件名
                                //uploadFileName
                                auction.setAuctionPic(uploadFileName);
                                int indexof = uploadFileName.lastIndexOf(".");
                                auction.setAuctionPicType(uploadFileName.substring((indexof + 1)));
                            }
                        }
                    } else {//普通表单元素
                        fieldName = item.getFieldName();   //表单字段的name属性值
                        if (fieldName.equals("auctionName")) {
                            //输出表单字段的值
                            auction.setAuctionName(item.getString("UTF-8"));
                            //easyBuy_ProductUpdate.setName(item.getString("UTF-8"));
                        }
                        if (fieldName.equals("startPrice")) {
                            auction.setAuctionStartPrice(Double.valueOf(item.getString("UTF-8")));
                            //easyBuy_ProductUpdate.setCategoryLevell(Integer.valueOf(item.getString("UTF-8")));
                        }
                        if (fieldName.equals("upset")) {
                            // easyBuy_ProductUpdate.setCategoryLevel2(Integer.valueOf(item.getString("UTF-8")));
                            auction.setAuctionUpset(Double.valueOf(item.getString("UTF-8")));
                        }
                        if (fieldName.equals("startTime")) {
                            // easyBuy_ProductUpdate.setCategoryLevel3(Integer.valueOf(item.getString("UTF-8")));
                            auction.setAuctionStartTime(simpleDateFormat.parse(item.getString("UTF-8")));
                        }
                        if (fieldName.equals("endTime")) {
                            // easyBuy_ProductUpdate.setStock(Integer.valueOf(item.getString("UTF-8")));
                            auction.setAuctionEndTime(simpleDateFormat.parse(item.getString("UTF-8")));
                        }
                        if (fieldName.equals("desc")) {
                            auction.setAuctionDesc(item.getString("UTF-8"));
                            // easyBuy_ProductUpdate.setPrice(Double.parseDouble(item.getString("UTF-8")));
                        }
                        //aId
                        if (fieldName.equals("aId")) {
                            auction.setAuctionId(Long.valueOf(item.getString("UTF-8")));
                            // easyBuy_ProductUpdate.setPrice(Double.parseDouble(item.getString("UTF-8")));
                        }

                    }
                }
            } catch (FileUploadBase.SizeLimitExceededException ex) {
                out.print("上传失败，文件太大，单个文件的最大限制是：" + upload.getSizeMax() + "bytes!");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        int result=auctionBiz.UpdateAuction(auction);
        if(result>0){
            return "redirect:/do/auction/auctionList";
        }else{
            return "redirect:/addAuction.jsp";
        }

    }
    //删除
    public void DeleteAuction(HttpServletRequest request,HttpServletResponse response) throws SQLException, IOException {
        PrintWriter out = response.getWriter();
        int dId=Integer.valueOf(request.getParameter("dId"));
        System.out.println(dId);
        int result=auctionBiz.deleteAuction(dId);
        boolean flag=false;
        if(result>0){
            flag=true;
        }
        System.out.println(flag);
        out.print(flag);
    }
    //查看竞拍
    public String AuctionDetail(HttpServletRequest request,HttpServletResponse response) throws IOException, SQLException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        String auctionId=request.getParameter("auctionId");
                Auction auction=auctionBiz.ShowAuctionById(Integer.valueOf(auctionId));
                List<Auctionrecord> listAuctionrecord=auctionBiz.showAuctionrecord(Integer.valueOf(auctionId));
                for(Auctionrecord auctionrecord:listAuctionrecord){
                    System.out.println(auctionrecord.getAuctionPrice()+""+auctionrecord.getUserName()+""+auctionrecord.getAuctionTime());
                }
                request.setAttribute("newPaiInfo",listAuctionrecord);
                request.setAttribute("auctionInfo",auction);
                return "forward:/auctionDetail.jsp";

    }
    //新增竞拍信息
    public void AddAuctionrecord(HttpServletRequest request,HttpServletResponse response) throws SQLException, IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        int result=auctionBiz.AddAuctionrecord(Integer.valueOf(request.getParameter("userId")),Integer.valueOf(request.getParameter("auctionId")),Double.valueOf(request.getParameter("auctionPrice")));
        boolean flag=false;
        if(result>0){
            flag=true;
        }
        out.print(flag);
    }
    //查看拍卖结束的商品信息
    public String AuctionResult(HttpServletRequest request,HttpServletResponse responsee) throws SQLException {
        List<EndAuction> listEndAuction=auctionBiz.showEndTimeAuction();
        List<Auction> listAuctionTime=auctionBiz.showAllAuctio("456");
        List<EndAuction> listEndAName=auctionBiz.showAuctionNowTime();
        System.out.println(listEndAName.size());
        //listEndAName
        request.getSession().setAttribute("listEndAName",listEndAName);
        request.getSession().setAttribute("listAuctionTime",listAuctionTime);
        request.getSession().setAttribute("listEndAuction",listEndAuction);
        return "redirect:/auctionResult.jsp";
    }

}

